import websocket from '../../utils/websocket';

Page({
  data: {
    groupId: '',
    messages: [],
    inputValue: '',
    loading: false
  },

  onLoad(options) {
    this.setData({
      groupId: options.groupId
    });
    this.loadMessages();
    this.setupWebSocket();
    // 发送用户状态更新
    this.updateUserStatus(options.groupId);
  },

  onUnload() {
    // 离开群聊页面时，清除当前群组ID
    this.updateUserStatus('');
  },

  // 更新用户状态
  updateUserStatus(groupId) {
    const message = {
      type: 'USER_STATUS',
      fromUserId: wx.getStorageSync('userId'),
      groupId: groupId,
      timestamp: Date.now()
    };
    websocket.send(message);
  },

  // 加载历史消息
  async loadMessages() {
    this.setData({ loading: true });
    try {
      const token = wx.getStorageSync('token');
      const response = await wx.request({
        url: `http://your-server-address:8080/api/chat/messages/group/${this.data.groupId}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.statusCode === 200) {
        this.setData({
          messages: response.data
        });
      } else {
        wx.showToast({
          title: '获取消息历史失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取消息历史错误:', error);
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 设置WebSocket连接
  setupWebSocket() {
    const token = wx.getStorageSync('token');
    websocket.connect(token);

    // 注册群聊消息处理器
    websocket.onMessage('GROUP_CHAT', (data) => {
      if (data.groupId === this.data.groupId) {
        this.receiveMessage(data);
      }
    });
  },

  // 接收新消息
  receiveMessage(message) {
    const messages = this.data.messages;
    messages.push(message);
    this.setData({ messages });
    
    // 滚动到底部
    wx.createSelectorQuery()
      .select('#message-list')
      .boundingClientRect((rect) => {
        wx.pageScrollTo({
          scrollTop: rect.height,
          duration: 300
        });
      })
      .exec();
  },

  // 发送消息
  sendMessage() {
    if (!this.data.inputValue.trim()) return;

    const message = {
      type: 'GROUP_CHAT',
      fromUserId: wx.getStorageSync('userId'),
      groupId: this.data.groupId,
      content: this.data.inputValue,
      timestamp: Date.now()
    };

    // 通过WebSocket发送消息
    websocket.send(message);

    // 清空输入框
    this.setData({
      inputValue: ''
    });
  },

  // 输入框内容变化
  onInput(e) {
    this.setData({
      inputValue: e.detail.value
    });
  }
});